package com.lzq.badminton.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzq.badminton.Exception.SystemException;
import com.lzq.badminton.dto.LoginDto;
import com.lzq.badminton.entity.UserAdmin;
import com.lzq.badminton.enums.AppHttpCodeEnum;
import com.lzq.badminton.mapper.UserAdminMapper;
import com.lzq.badminton.service.UserAdminService;
import com.lzq.badminton.utils.BeanCopyUtils;
import com.lzq.badminton.utils.JwtUtil;
import com.lzq.badminton.vo.LoginVo;
import com.lzq.badminton.vo.UserInfoVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserAdminServiceImpl extends ServiceImpl<UserAdminMapper, UserAdmin> implements UserAdminService {

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public LoginVo login(LoginDto loginDto) {
        String password = loginDto.getPassword();
        LambdaQueryWrapper<UserAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAdmin::getUsername, loginDto.getUsername());
        UserAdmin one = getOne(lambdaQueryWrapper);
        if(passwordEncoder.matches(password, one.getPassword())){
            //登录成功,开始加密
            Map<String, Object> claim = new HashMap<>();
            claim.put("userId", one.getId());
            String token = JwtUtil.createJWT("hello", 1000 * 60 * 60, claim);
            LoginVo loginVo = new LoginVo(one.getUsername(), token, one.getAvatar());
            return loginVo;
        }
        throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
    }

    @Override
    public void register(LoginDto loginDto) {
        String encode = passwordEncoder.encode(loginDto.getPassword());
        loginDto.setPassword(encode);
        UserAdmin userAdmin = BeanCopyUtils.copyBean(loginDto, UserAdmin.class);
        save(userAdmin);
    }

    @Override
    public UserInfoVo getUserInfo(String token) {
        Claims claims = JwtUtil.parseJWT("hello", token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        UserAdmin userAdmin = getById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(userAdmin, UserInfoVo.class);
        return userInfoVo;
    }
}
